<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\CarPackageUsedLog;
use App\Admin\Services\AdminUserService;
use App\Models\CarPackageOrder;
use App\Models\CarPackageOrderAttr;
use App\Models\Store;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\OperationLog\Models\OperationLog;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Auth;

class CarPackageUsedLogController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $request = request();

        return Grid::make(CarPackageUsedLog::with(['order', 'store', 'operator', 'attr']), function (Grid $grid) use ($request) {
            if ($request->has('user_id')) {
                $grid->model()->where('user_id', $request->get('user_id'));
            }

            if ($request->has('operator_user_id')) {
                $grid->model()->where('operator_user_id', $request->get('operator_user_id'));
            }

            if ($request->has('order_id')) {
                $grid->model()->where('order_id', $request->get('order_id'));
            }

            if ($request->has('attr_id')) {
                $grid->model()->where('attr_id', $request->get('attr_id'));
            }

            $package_id = AdminUserService::permissionOrders(Auth::guard('admin')->user()->username);

            if ($package_id) {
                $grid->model()->whereIn('package_id', $package_id);
            }

            $grid->column('id')->sortable();
            $grid->column('order.id', admin_trans('car-package-used-log.fields.order_id'));
            $grid->column('order.user_name', admin_trans('car-package-used-log.fields.user_id'));
            $grid->column('attr.attr_title', admin_trans('car-package-used-log.fields.attr_id'));
            $grid->column('status')->using(admin_trans('car-package-used-log.options.status'))->badge([
                0 => 'primary',
                1 => 'success',
            ]);
            $grid->column('operator.name', admin_trans('car-package-used-log.fields.operator_user_id'));
            $grid->export();

            $grid->model()->orderBy('id', 'desc');

            $grid->export()->rows(function ($rows) {
                foreach ($rows as $index => &$row) {
                    $row['status'] = usedStatusSwitchTitle($row['status']);
                }

                return $rows;
            });

            if ($request->has('operator_user_id')) {
                $grid->column('operator_at')->sortable();
            } else {
                $grid->column('used_at')->sortable();
            }

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('user.name', admin_trans('car-package-used-log.fields.user_id'));
                $filter->like('store.title', admin_trans('car-package-used-log.fields.store_id'));
                $filter->like('operatorUser.name', admin_trans('car-package-used-log.fields.operator_user_id'));
                $filter->equal('status')->select(admin_trans('car-package-used-log.options.status'));
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                // 当前行的某个字段的数据
                $status = $actions->row->status;

                if ($status == DEFAULT_TYPE_ZERO) {
                    $url = config('app.url')."/admin/car-package-used-log/{$actions->getKey()}/edit";
                    $actions->append("<a href='{$url}' class='fa fa-paper-plane' data-id='{$actions->getKey()}'><i class='fa'></i> 核销</a>");
                }
            });

            $grid->disableEditButton();
            $grid->disableDeleteButton();
            $grid->disableCreateButton();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, CarPackageUsedLog::with(['order', 'store', 'operator', 'attr']), function (Show $show) {
            $show->field('id');
            $show->field('attr.attr_title', admin_trans('car-package-used-log.fields.attr_id'));
            $show->field('order.user_name', admin_trans('car-package-order-attr.fields.user_id'));
            $show->field('operator.name', admin_trans('car-package-used-log.fields.operator_user_id'));
            $show->field('operator_pics')->unescape()->as(function ($operator_pics) {
                $json_arr = json_decode($operator_pics, true);
                $str = '';

                if($json_arr) {
                    foreach ($json_arr as $key => $value) {
                        $str .=  "<img width=200 src='".$json_arr[0]['url']."' />";
                    }
                }

                return $str;
            });
            $show->field('remarks');
            $show->field('status')->using(admin_trans('car-package-used-log.options.status'));
            $show->field('used_at');
            $show->field('operator_at');
//            $show->field('created_at');
            $show->field('updated_at');

            $show->panel()->tools(function ($tools) {
                $tools->disableDelete();
                $tools->disableEdit();
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CarPackageUsedLog(), function (Form $form) {
//            $form->display('id');
            $form->text('order_id')->customFormat(function ($order_id) {
                $order = CarPackageOrder::find($order_id);
                return $order->order_id;
            })->disable();
            $form->text('package_title')->disable();
            $form->text('attr_id')->customFormat(function ($attr_id) {
                $attr = CarPackageOrderAttr::find($attr_id);
                return $attr->attr_title;
            })->disable();
//            $form->image('package_pic')->disable();
            $form->text('car_number')->disable();
            $form->text('store_id')->customFormat(function ($store_id) {
                $store = Store::find($store_id);
                return $store->title;
            })->disable();
            $form->text('operator_user_id')->customFormat(function ($operator_user_id) {
                $user = User::find($operator_user_id);
                return $user->name;
            })->disable();
            $form->text('remarks')->disable();
            $form->multipleImage('operator_pics')->customFormat(function ($operator_pics) {
                $urls = [];
                foreach ($operator_pics as $key => $value) {
                    $urls[] = $value['url'];
                }

                return $urls;
            })->disable();
            $form->text('operator_at')->disable();
            $form->text('used_at')->disable();
            $form->radio('status')->options(admin_trans('car-package-used-log.options.status'))->default('1');

            $form->tools(function (Form\Tools $tools) {
                $tools->disableDelete();
            });

            $form->saving(function ($form) {
                if ($form->status == DEFAULT_STATUS_SUCCESS) {
                    $attr = CarPackageOrderAttr::find($form->model()->attr_id);

                    if ($attr->usable_number == 0) {
                        return $form->response()->error('该服务属性可用次数已用尽!');
                    } else {
                        $attr->usable_number = $attr->usable_number - 1;
                        $attr->used_number = $attr->used_number + 1;

                        $attr->save();
                    }
                }

                $form->deleteInput('operator_pics');
                $form->model()->admin_user_id = Auth::guard('admin')->user()->id;
            });

            $status = $form->model()->status;

            $form->saved(function (Form $form) use ($status) {
                $operation = OperationLog::where('user_id', Auth::guard('admin')->user()->id)
                    ->where('method', 'PUT')
                    ->orderBy('id', 'desc')
                    ->first();

                $operation->content = json_encode([
                    'status' => $status
                ]);

                $operation->save();
            });
//            $form->display('created_at');
//            $form->display('updated_at');
        });
    }
}
